package cn.qicaiwang.open.qxyApi.server.Impl;


import cn.qicaiwang.open.common.response.ResponseResult;
import cn.qicaiwang.open.common.utils.StringUtils;
import cn.qicaiwang.open.qxyApi.entity.EnterpriseInfo;
import cn.qicaiwang.open.qxyApi.mapper.AccessTokenMapper;
import cn.qicaiwang.open.qxyApi.mapper.EnterpriseInfoMapper;
import cn.qicaiwang.open.qxyApi.server.EnterpriseInfoService;
import cn.qicaiwang.open.qxyApi.util.ApiServer;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class EnterpriseInfoServiceImpl implements EnterpriseInfoService {


    @Autowired
    private EnterpriseInfoMapper enterpriseInfoMapper;
    @Autowired
    private ApiServer apiServer; // 注入ApiServer


    // 企业联系信息
    @Override
    public ResponseResult getCompanyContactInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {

        return getEnterpriseInfo(companyName, "contactInfo", "/v2/insight/companyContactInfo", pageNum, pageSize,"企业联系信息",userId);
    }

    // 工商基本信息
    @Override
    public ResponseResult getBizBasicInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {

        return getEnterpriseInfo(companyName, "bizBasicInfo", "/v2/insight/info", pageNum, pageSize,"工商基本信息",userId);
    }

    // 股东出资信息
    @Override
    public ResponseResult getShareholderInvest(String companyName, Integer pageNum, Integer pageSize ,String userId) {
        return getEnterpriseInfo(companyName, "shareHolderInverst", "/v2/insight/shareholderInvest", pageNum, pageSize,"股东出资信息",userId);
    }


    // 对外投资信息
    @Override
    public ResponseResult getInvestmentAbroad(String companyName, Integer pageNum, Integer pageSize ,String userId) {
        return getEnterpriseInfo(companyName, "investInfo", "/v2/insight/investmentAbroad", pageNum, pageSize,"对外投资信息",userId);
    }

    // 税务重大违法信息
    @Override
    public ResponseResult getTaxBigIllegal(String companyName, Integer pageNum, Integer pageSize ,String userId) {
        return getEnterpriseInfo(companyName, "taxViolation", "/v2/insight/taxBigIllegal", pageNum, pageSize,"税务重大违法信息",userId);
    }

    // 资质证书信息
    @Override
    public ResponseResult getCertificateInfo(String companyName, Integer pageNum, Integer pageSize ,String userId) {
        return getEnterpriseInfo(companyName, "certInfo", "/v2/insight/certificateInfo", pageNum, pageSize,"资质证书信息",userId);
    }

    // 失信信息
    @Override
    public ResponseResult getDishonestyInfo(String companyName, Integer pageNum, Integer pageSize ,String userId) {
        return getEnterpriseInfo(companyName, "dishonestInfo", "/v2/insight/dishonestyInfo", pageNum, pageSize,"失信信息",userId);
    }

    // 限制高消费信息
    @Override
    public ResponseResult getLimitHighConsumerInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "highConsumeLimit", "/v2/insight/limitHighConsumerInfo", pageNum, pageSize,"限制高消费信息",userId);
    }

    // 限制高消费关联企业信息
    @Override
    public ResponseResult getLimitHighConsumerRelation(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "highConsumeRelated", "/v2/insight/limitHighConsumerRelationEn", pageNum, pageSize,"限制高消费关联企业信息",userId);
    }

    // 裁判文书信息
    @Override
    public ResponseResult getJudgmentDoc(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "judicialDocs", "/v2/insight/judgmentDoc", pageNum, pageSize,"裁判文书信息",userId);
    }

    // 欠税公告信息
    @Override
    public ResponseResult getOweTaxInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "taxArrears", "/v2/insight/oweTaxInfo", pageNum, pageSize,"欠税公告信息",userId);
    }

    // 税务非正常户信息
    @Override
    public ResponseResult getTaxUnNormalInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "taxAbnormal", "/v2/insight/taxUnNormalInfo", pageNum, pageSize,"税务非正常户信息",userId);
    }

    // 行政处罚信息
    @Override
    public ResponseResult getAdministrationPenalty(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "adminPenalty", "/v2/insight/administrationPenalty", pageNum, pageSize,"行政处罚信息",userId);
    }

    // 经营异常名录信息
    @Override
    public ResponseResult getAbnormalBiz(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "abnormalBiz", "/v2/insight/exceptionList", pageNum, pageSize,"经营异常名录信息",userId);
    }

    // 经营异常列入移出公告
    @Override
    public ResponseResult getRemoveExceptionList(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "abnormalAnnounce", "/v2/insight/removeExceptionList", pageNum, pageSize,"经营异常列入移出公告",userId);
    }

    // 严重违法失信企业名单
    @Override
    public ResponseResult getSeriousIllegalBlackInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "seriousDiscredit", "/v2/insight/seriousIllegalBlackInfo", pageNum, pageSize,"严重违法失信企业名单",userId);
    }

    // 商标信息
    @Override
    public ResponseResult getTrademarkInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "trademarkInfo", "/v2/insight/trademarkInfo", pageNum, pageSize,"商标信息",userId);
    }

    // 专利信息
    @Override
    public ResponseResult getPatentInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "patentInfo", "/v2/insight/patentInfo", pageNum, pageSize,"专利信息",userId);
    }

    // 专利关系信息
    @Override
    public ResponseResult getPatentRelationInfo(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "patentRelation", "/v2/insight/patentRelationInfo", pageNum, pageSize,"专利关系信息",userId);
    }

    // 专利法律状态信息
    @Override
    public ResponseResult getPatentLawStatus(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "patentStatus", "/v2/insight/patentLawStatus", pageNum, pageSize,"专利法律状态信息",userId);
    }

    // A类纳税人信息
    @Override
    public ResponseResult getTaxpayerLevelA(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "aTaxpayer", "/v2/insight/taxpayerLevelA", pageNum, pageSize,"A类纳税人信息",userId);
    }

    //行政许可信息
    @Override
    public ResponseResult getadministrativeLicense(String companyName, Integer pageNum, Integer pageSize,String userId) {
        return getEnterpriseInfo(companyName, "administrativeLicense", "/v2/insight/administrativeLicense", pageNum, pageSize,"行政许可信息",userId);

    }

    private ResponseResult getEnterpriseInfo(String name, String fieldName, String apiPath, Integer pageNum, Integer pageSize,String apiName,String userId) {
        //1.查询是否由可以用次数
        Integer  PackageCount= enterpriseInfoMapper.getPackageCount(userId);
        if (PackageCount ==0) {
            return ResponseResult.ok("已无企业查询可用次数，请充值后再试");
        }
        int updatedCount = PackageCount - 1;

        // 1. 先查数据库
        EnterpriseInfo enterpriseInfo = enterpriseInfoMapper.selectByCompanyName(name);

        if (enterpriseInfo != null) {
            try {
                // 使用反射获取字段值
                Field field = EnterpriseInfo.class.getDeclaredField(fieldName);
                field.setAccessible(true);
                String fieldValue = (String) field.get(enterpriseInfo);

                if (StringUtils.isNotBlank(fieldValue)) {
                    // 解析数据库存储的 JSON
                    Object data = JSONObject.parse(fieldValue);
                    // 更新减1后的次数回数据库
                    enterpriseInfoMapper.updatePackageCount(userId, updatedCount);
                    return handleDataPagination(data, pageNum, pageSize);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseResult.error("数据库字段读取失败");
            }
        }

        // 2. 数据库没有则调用第三方API
        try {
            JSONObject requestBody = new JSONObject();
            requestBody.put("name", name);

            JSONObject apiResult = apiServer.callApi(apiPath, requestBody.toJSONString(),apiName);
            System.out.println(apiResult);
            if (apiResult == null) {
                return ResponseResult.error("未从API获取到有效数据");
            }

            Object data = apiResult.get("data");
            if (data == null) {
                return ResponseResult.empty("API返回数据中data字段为空");
            }

            // 3. 保存到数据库
            if (enterpriseInfo == null) {
                enterpriseInfo = new EnterpriseInfo();
                enterpriseInfo.setCompanyName(name);
                enterpriseInfo.setCreateTime(new Date());
            }

            try {
                Field field = EnterpriseInfo.class.getDeclaredField(fieldName);
                field.setAccessible(true);

                String valueToStore;
                if (data instanceof JSONArray) {
                    valueToStore = JSONObject.toJSONString(data);
                } else if (data instanceof JSONObject) {
                    valueToStore = ((JSONObject) data).toJSONString();
                } else {
                    valueToStore = data.toString();
                }

                field.set(enterpriseInfo, valueToStore);
            } catch (Exception e) {
                return ResponseResult.error("设置字段值失败");
            }

            // 判断是否需要新增或更新
            if (enterpriseInfo.getId() == null) {
                enterpriseInfoMapper.insert(enterpriseInfo);
            } else {
                enterpriseInfoMapper.updateById(enterpriseInfo);
            }
            // 更新减1后的次数回数据库
            enterpriseInfoMapper.updatePackageCount(userId, updatedCount);
            return handleDataPagination(data, pageNum, pageSize);
        } catch (Exception e) {
            return ResponseResult.error("获取企业信息失败");
        }
    }

    /**
     * 统一处理数据分页逻辑
     */
    private ResponseResult handleDataPagination(Object data, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10; // 默认每页 10 条
        }

        JSONArray itemsArray = null;
        JSONObject resultObj = new JSONObject();
        int total = 0;

        // 情况1：data是包含items数组的JSONObject
        if (data instanceof JSONObject) {
            JSONObject dataObj = (JSONObject) data;

            // 检查是否存在items数组
            if (dataObj.containsKey("items") && dataObj.get("items") instanceof JSONArray) {
                itemsArray = dataObj.getJSONArray("items");
                total = itemsArray.size();

                // 保留原始数据中的其他字段
                for (Map.Entry<String, Object> entry : dataObj.entrySet()) {
                    if (!"items".equals(entry.getKey())) {
                        resultObj.put(entry.getKey(), entry.getValue());
                    }
                }
            }
        }
        // 情况2：data本身就是JSONArray
        else if (data instanceof JSONArray) {
            itemsArray = (JSONArray) data;
            total = itemsArray.size();
        }

        // 如果没有可分页的数组，直接返回原始数据
        if (itemsArray == null) {
            return ResponseResult.ok(data);
        }

        // 计算分页范围
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        // 处理超出范围的情况
        if (fromIndex >= total) {
            resultObj.put("items", new JSONArray());
            resultObj.put("total", total);
            resultObj.put("pageNum", pageNum);
            resultObj.put("pageSize", pageSize);
            return ResponseResult.ok(resultObj);
        }

        // 提取当前页数据
        JSONArray pagedItems = new JSONArray();
        for (int i = fromIndex; i < toIndex; i++) {
            pagedItems.add(itemsArray.get(i));
        }

        // 构建返回结果
        resultObj.put("items", pagedItems);
        resultObj.put("total", total);
        resultObj.put("pageNum", pageNum);
        resultObj.put("pageSize", pageSize);

        return ResponseResult.ok(resultObj);
    }
}




